package cn.kgc.fcm.dsbank.controller;

import cn.kgc.fcm.dsbank.condition.CustomerCondition;
import cn.kgc.fcm.dsbank.dto.ResultDTO;
import cn.kgc.fcm.dsbank.entity.Certificate;
import cn.kgc.fcm.dsbank.entity.Customer;
import cn.kgc.fcm.dsbank.entity.ProvinceCityDistrict;
import cn.kgc.fcm.dsbank.entity.Syslog;
import cn.kgc.fcm.dsbank.exception.SysException;
import cn.kgc.fcm.dsbank.service.CertificateService;
import cn.kgc.fcm.dsbank.service.CustomerService;
import cn.kgc.fcm.dsbank.service.ProvinceCityDistrictService;
import cn.kgc.fcm.dsbank.service.SyslogService;
import cn.kgc.fcm.dsbank.utils.Pager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController{

    private final static Logger log = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ProvinceCityDistrictService pctService;

//    @Autowired
//    private SyslogService syslogService;

    @Autowired
    private CertificateService certificateService;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @RequestMapping("/show_all_custom")
    public String showCustomer(Model model, CustomerCondition condition, Pager pager){

//        Syslog syslog = new Syslog();
//        syslog.setEmpId(this.getLoginedEmp().getEmpId());
//        syslog.setOperatorTime(new Date());
//        syslog.setMethodName("showCustomer");
//        syslog.setVisitUrl("//customer/show_all_custom");
//        syslogService.addSyslog(syslog);


        ResultDTO<List<Customer>> customerListResultDTO = customerService.selectCustomerAll(condition,pager);

        model.addAttribute("result",customerListResultDTO);

        model.addAttribute("pager",pager);


        return "/customer/show_customer";
    }
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @RequestMapping("/show_customer_one/{customerId}")
    public String showCustomerOne(@PathVariable Long customerId,Model model){
        ResultDTO<Customer> customerResultDTO = customerService.selectCustomerByCustomerId(customerId);
        model.addAttribute("result",customerResultDTO);
        return "/customer/show_customer_one";
    }


    @RequestMapping("/add_custom")
    public String addCustomer(Model model){
        ResultDTO<List<ProvinceCityDistrict>> listResultDTO = pctService.selectProvinceCityDistrictByPid(0);

        List<Certificate> certificates = certificateService.selectCertificateAll();
        model.addAttribute("provinces",listResultDTO.getObj());
        model.addAttribute("certificates",certificates);

        return "/customer/add_customer";
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @RequestMapping("/do_add_customer")
    public String doAddCUstomer(@Valid Customer customer, BindingResult errors, MultipartFile upload, HttpServletRequest request) throws IOException, SysException {

        if(errors.hasErrors()){

            List<FieldError> list = errors.getFieldErrors();
            for (FieldError fieldErr: list) {
                String name = fieldErr.getField();
                String msg = fieldErr.getDefaultMessage();
                System.out.println(name+"\t"+msg);
                throw new SysException(msg);
            }
        }

        //定义身份证上传路径
        String path = request.getServletContext().getRealPath("/customer_id_img");
        //创建File对象
        File file = new File(path);
        //根据设置的路径地址，创建目录
        if(!file.exists()){
            file.mkdir();
        }
        //获取上传文件的文件名
        String originalFilename = upload.getOriginalFilename();

        String uuid = UUID.randomUUID().toString().replace("-", "");
        //设定上传文件的存储屋内按名
        String fileName = uuid+"_"+originalFilename;
        //将上传文件的地址及名称存入客户对象
        customer.setIdImgUrl("/customer_id_img/"+fileName);
        //完成上传
        upload.transferTo(new File(path,fileName));



        //将客户添加人id存入客户对象
        customer.setCreateEmpId(this.getLoginedEmp().getEmpId());
        ResultDTO resultDTO = customerService.addCustomer(customer);

//        log.info("图片位置:{}",customer.getIdImpUrl());
        
        return "redirect:/customer/show_all_custom";
    }




}
